<template>
    <div>
        <el-table
            ref="singleTable"
            :data="tableData"
            border
            :default-sort="{prop: 'date', order: 'descending'}"
            style="width: 100%"
            class="table-line-clamp"
            show-summary
            :summary-method="getSummaries"
            v-bind="$attrs"
            v-on="$listeners"
        >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('from_time')"
                prop="from_time"
                key="from_time"
                label="借款时间"
                sortable
            >
                <template v-slot="{row}">
                    {{ moment(row.from_time).format(THE_MOMENT_YYMMDD_HHMM) }}
                </template>
            </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('platform')"
                prop="platform"
                key="platform"
                label="借款平台"
                sortable
            >
                <template v-slot="{row}">
                    <el-button
                        :disabled="!row._id"
                        @click="$router.push({name: PLATFORM, query: {name: row.platform ? row.platform.name : ''}})"
                        type="text"
                        style="user-select: unset;"
                    >
                        {{ row.platform ? row.platform.name : '' }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column v-if="checkedValues.includes('name')" prop="name" key="name" label="账单名称" sortable>
                <template v-slot="{row}">
                    <el-button :disabled="!row._id" @click="handleDetail(row)" type="text" style="user-select: unset;">
                        {{ row.name }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('current.status')"
                prop="current.status"
                key="current.status"
                label="账单状态"
                sortable
            >
                <template v-slot="{row}">
                    <span :class="row.current.status | handleGetTheBillClassnameByTotalStatus">
                        {{ row.current.status | handleGetBillStatusTextByStatus }}
                    </span>
                </template>
            </el-table-column>
            <!-- 还款时间 -->
            <el-table-column
                v-if="checkedValues.includes('create_date')"
                prop="create_date"
                key="create_date"
                label="创建时间"
                sortable
            >
                <template v-slot="{row}">
                    {{
                        row.current.status === BILL_STATUS_SETTLED
                            ? '-'
                            : moment(row.create_date).format(THE_MOMENT_YYMMDD)
                    }}
                </template>
            </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('current.date')"
                prop="current.date"
                key="current.date"
                label="还款日期"
                sortable
            >
                <template v-slot="{row}">
                    {{
                        row.current.status === BILL_STATUS_SETTLED
                            ? '-'
                            : moment(row.current.date).format(THE_MOMENT_YYMMDD)
                    }}
                </template>
            </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('current.cash')"
                prop="current.cash"
                key="current.cash"
                label="本期待还"
                sortable
            >
                <template v-slot="{row}">
                    {{ row.current.status === BILL_STATUS_SETTLED ? '-' : row.current.cash }}
                </template>
            </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('current.stage')"
                prop="current.stage"
                key="current.stage"
                label="当前期数/总期数"
                sortable
            >
                <template v-slot="{row}">
                    {{ `${row.current.status === BILL_STATUS_SETTLED ? '-' : row.current.stage}/${row.stage_total}` }}
                </template>
            </el-table-column>
            <el-table-column v-if="checkedValues.includes('total')" prop="total" key="total" label="借款金额" sortable>
            </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('total_all')"
                prop="total_all"
                key="total_all"
                label="合计需还"
                sortable
            >
            </el-table-column>
            <el-table-column v-if="checkedValues.includes('rate')" prop="rate" key="rate" label="综合年化费率" sortable>
                <template v-slot="{row}">
                    {{ `${row.rate}%` }}
                </template>
            </el-table-column>

            <el-table-column v-if="checkedValues.includes('bank')" prop="bank" key="bank" label="还款银行" sortable>
                <template v-slot="{row}">
                    {{ `${row.bank}(${row.bank_number})` }}
                </template>
            </el-table-column>
            <el-table-column v-if="checkedValues.includes('remark')" prop="remark" key="remark" label="备注" sortable>
                <!-- <template v-slot="{row}">
                    {{ row.remark && row.remark.length >= 30 ? `${row.remark.slice(0, 30)}...` : row.remark }}
                </template> -->
            </el-table-column>

            <el-table-column v-if="checkedValues.includes('operation')" key="operation" align="center" label="操作">
                <template v-slot="{row}">
                    <el-button @click="handleDetail(row)" type="text">
                        查看
                    </el-button>
                    <el-button :disabled="!isOperation" @click="handleEdit(row)" type="text">
                        编辑
                    </el-button>
                    <el-button :disabled="!isOperation" @click="handleShowDeleteDialog(row)" type="text">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            :pageSizes="[5, 10, 20, 30, 50, 100, 200]"
            @change="onChangePage"
        />
        <CreateBill
            title="编辑账单"
            :data-source="dataSouceEdit"
            :visible.sync="centerDialogVisibleEdit"
            @on-ok="getList"
            @close="dataSouceEdit = {}"
            :optionsPlatforms="optionsPlatforms"
        >
        </CreateBill>
        <CreateBill
            title="查看账单"
            :data-source="dataSouceDetail"
            :visible.sync="centerDialogVisibleDetail"
            @close="dataSouceDetail = {}"
            :optionsPlatforms="optionsPlatforms"
        >
        </CreateBill>
        <TheElDialog title="删除账单" :visible.sync="dialogVisible">
            <span>你确定删除 {{ currentRow.name }}？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="dialogLoading" type="primary" @click="handleDelete(currentRow)">确 定</el-button>
            </span>
        </TheElDialog>
    </div>
</template>
<script>
import {handleGetBillStatusTextByStatus, handleGetTheBillClassnameByTotalStatus} from '@/views/bill/filters-bill';
import moment from 'moment';
import {getBill, deleteBill} from '@/api/bill';
import {BASIC_MONEY, THE_MOMENT_YYMMDD_HHMM, THE_MOMENT_YYMMDD} from '@/utils/constant';
import CreateBill from '@/views/bill/CreateBill';
import {BILL_DETAIL, PLATFORM} from '@/router/route-name';
import {mixinIsOperation} from '@/mixins';
import {BILL_STATUS_SETTLED} from '@/views/bill/constant-bill';

export default {
    name: 'the-bill-table',
    props: {
        optionsPlatforms: {
            type: Array,
            required: true,
            default: () => []
        },
        formSearch: {
            type: Object,
            required: true
        },
        getList: {
            type: Function,
            required: true
        },
        tableData: {
            type: Array,
            required: true
        },
        checkedValues: {
            type: Array,
            required: true
        }
    },
    components: {
        CreateBill
    },
    filters: {
        handleGetBillStatusTextByStatus,
        handleGetTheBillClassnameByTotalStatus
    },
    mixins: [mixinIsOperation],
    data() {
        return {
            PLATFORM,
            THE_MOMENT_YYMMDD_HHMM,
            THE_MOMENT_YYMMDD,
            BILL_STATUS_SETTLED,
            moment,
            // 编辑账单数据
            dataSouceEdit: {},
            // 查看详情账单数据
            dataSouceDetail: {},
            // 删除账单对话框
            dialogVisible: false,
            // 删除账单对话框 loading
            dialogLoading: false,
            // 当前的账单数据
            currentRow: {},
            // 编辑账单
            centerDialogVisibleEdit: false,
            // 查看详情
            centerDialogVisibleDetail: false
        };
    },
    methods: {
        clearSelection() {
            this.$refs.singleTable.clearSelection();
        },
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.some(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr * BASIC_MONEY;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = sums[index] / BASIC_MONEY;
                } else {
                    sums[index] = 'N/A';
                }
            });

            return sums;
        },
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        // 获取账单详情
        handleDetail(row) {
            // this.centerDialogVisibleDetail = true;
            // this.handleGetBill(row, 'dataSouceDetail');
            this.$router.push({name: BILL_DETAIL, query: {type: 'detail', id: row._id}});
        },
        // 获取单条账单信息
        handleEdit(row) {
            this.centerDialogVisibleEdit = true;
            this.handleGetBill(row, 'dataSouceEdit');
        },

        // 获取单条账单信息
        handleGetBill(row, key) {
            getBill(row._id).then(({data: res}) => {
                if (res.status === 200) {
                    const newBill = {
                        ...res.data
                    };
                    newBill.total = newBill.total / BASIC_MONEY;
                    newBill.total_all = newBill.total_all / BASIC_MONEY;

                    newBill.stages = newBill.stages.map(item => {
                        return {...item, cash: item.cash / BASIC_MONEY};
                    });
                    this[key] = newBill;
                } else {
                    this.$message({showClose: true, type: 'errors', message: res});
                    throw new Error(res);
                }
            });
        },
        // 展示删除弹窗
        handleShowDeleteDialog(row) {
            this.dialogVisible = true;
            this.currentRow = row;
        },
        // 确认删除
        handleDelete(row) {
            this.dialogLoading = true;
            deleteBill(row._id)
                .then(res => {
                    this.dialogVisible = false;
                    this.$message({showClose: true, type: 'success', message: '删除成功'});
                    this.getList();
                    this.dialogLoading = false;
                })
                .catch(err => {
                    this.$message({showClose: true, type: 'error', message: '删除失败'});
                    console.log('err :', err);
                    this.dialogVisible = false;
                    this.dialogLoading = false;
                });
        }
    }
};
</script>
